#-*- coding: utf-8 -*-
import os.path as path
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _

from forms import LoginForm

base_dir = "forum"

def br_login(request):
    next = request.GET.get('next', reverse('forum_index'))
    code = request.GET.get('code',0)
    
    if code:
        code_message = _("You must be logged to access this content.")
    
    if request.method=="POST":
        form = LoginForm(data=request.POST)
        
        if form.is_valid():
            from django.contrib.auth import login
            login(request, form.get_user())
            
            if not next or '//' in next or ' ' in next:
                next = default_redirect
            
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect(next)
    else:
        form = LoginForm(request)
        request.session.set_test_cookie()
    
    return render_to_response(path.join(base_dir, "login.html"),
                              locals(),
                              context_instance=RequestContext(request))

def br_logout(request):
    from django.contrib.auth import logout
    logout(request)
    return HttpResponseRedirect(reverse('forum_index'))